package com.bruin.generator.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bruin.generator.util.FreemarkerUtil;
import com.bruin.generator.util.MapUtil;
import com.bruin.generator.util.StringUtils;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * GeneratorService
 *
 * @author bruin
 */
@Slf4j
@Service
public class GeneratorServiceImpl implements GeneratorService {

    String templateCpnfig = null;

    /**
     * 从项目中的JSON文件读取String
     *
     * @author bruin
     */
    @Override
    public String getTemplateConfig() throws IOException {
        templateCpnfig = null;
        if (templateCpnfig != null) {
        } else {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template.json");
            templateCpnfig = new BufferedReader(new InputStreamReader(inputStream))
                    .lines().collect(Collectors.joining(System.lineSeparator()));
            inputStream.close();
        }
        //log.info(JSON.toJSONString(templateCpnfig));
        return templateCpnfig;
    }

    /**
     * 根据配置的Template模板进行遍历解析，得到生成好的String
     *
     * @author bruin
     */
    @Override
    public Map<String, String> getResultByParams(Map<String, Object> params) throws IOException, TemplateException {
        Map<String, String> result = new HashMap<>(32);
        result.put("tableName", MapUtil.getString(params, "tableName"));
        JSONArray parentTemplates = JSONArray.parseArray(getTemplateConfig());
        for (int i = 0; i < parentTemplates.size(); i++) {
            JSONObject parentTemplateObj = parentTemplates.getJSONObject(i);
            //模板配置
//            System.err.println(parentTemplateObj.toString());
            for (int x = 0; x < parentTemplateObj.getJSONArray("templates").size(); x++) {
                JSONObject childTemplate = parentTemplateObj.getJSONArray("templates").getJSONObject(x);
                String content = FreemarkerUtil.processString(
                        parentTemplateObj.getString("group") + "/" + childTemplate.getString("name") + ".ftl", params);
//                System.err.println(params);
//                System.err.println("============"+childTemplate.getString("name")+"===============");

//                packageName = packageName.replace("\\.", "/");
//                System.err.println(packageName);
                StringJoiner join = new StringJoiner(File.separator);
                join.add("D:/code_generator");
                if (childTemplate.getString("resourceType").equals("0")) {
                    join.add("src" + File.separator + "main" + File.separator + "java");
                    String packageName = (String) params.get("packageName");
                    String moduleName = (String) params.get("moduleName");
                    join.add(StringUtils.packageToPath(packageName));
                    join.add(moduleName);
                    join.add(StringUtils.packageToPath(childTemplate.getString("module")));
                } else {
                    join.add("resources");
                    join.add(StringUtils.packageToPath(childTemplate.getString("module")));
                }
                System.err.println((String) params.get("tableName"));
                join.add(
                        StringUtils.upperCaseFirst(StringUtils.underlineToCamelCase((String) params.get("tableName")))
                                + childTemplate.getString("suffix")+ "."
                                + childTemplate.getString("extension"));
                if (childTemplate.getString("isGenerator").equals("1")) {
                    writeFile(content, join);
                }

//                if (!Files.exists(path)) {
//                    Path dir = path.getParent();
//                    if (!Files.exists(dir)) {
//                        System.err.println("目录："+dir+"，是否存在："+Files.exists(dir));
//                        Files.createDirectory(dir);
//                    }
//                }

//                System.err.println(content);
                result.put(childTemplate.getString("name"), content);
            }
        }
        return result;
    }

    /**
     * 写文件
     *
     * @param content 文件类容
     * @param join    路径
     */
    private void writeFile(String content, StringJoiner join) {
        Path path = Paths.get(join.toString());
//        System.err.println(join.toString());
        try {
            File file = new File(join.toString());
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
//                    writer = new FileWriter(file);

            Files.write(path, content.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
